<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'
import { computed, h, ref, onBeforeMount } from 'vue'
import { Page, useVbenModal, prompt } from '@vben/common-ui'
import { Button, message, Tag, Space, Radio, Input, Select, SelectOption, DatePicker, Cascader, Spin } from 'ant-design-vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import {
  getPurchaseIndex,
  getPurchaseIndex2,
  getPurchaseSum,
  getPurchaseSum2,
  savePurchaseProgress,
  saveProgressColumn,
  getSupplyOptions,
  getWarehouseOptions,
  getGoodsHeelMan,
  getMerchandiserDict,
  exportPurchaseProgress,
  exportPurchaseProgress2,
  getBatchMaterialDetail,
} from '#/api/goodsPurchaseProgress2'
import { useDebounceFn } from '@vueuse/core'
import SendGoodsSkuModalComponent from './modules/sendGoodsSkuModal.vue'
import Again from './modules/againModal.vue'
import SearchTemplate from '../modules/searchTemplate.vue'
import TypeLog from './modules/typeLog.vue'
import SearchTemplateSelect from '../modules/SearchTemplateSelect.vue'
import { saveSearchTemplate, listSearchTemplate } from '#/api/common'
import { getCategoryOptions, getTimeCategoryOptions } from '#/api/materialBatchBill'

import { copyToClipboard } from '@vben/utils'

interface RowType {
  [key: string]: any
}

const header_data = ref<any>([])
const field_data = ref<any>([])
const header_info = ref<any>([])
const selectedRows = ref<any>([])
const formData = ref<any>({})
const footerData = ref<any>([])
const keyword = ref({
  supply_id: '',
  warehouse_id: '',
  heel_man_name: '',
  merchandiser: '',
})

const dataType = ref('1') // 1:实时取数 2:快照取数

// 初始化时获取商品分类和时间分类选项
onBeforeMount(() => {
  fetchCategoryOptions()
  fetchTimeCategoryOptions()
})

// 获取商品分类选项
const fetchCategoryOptions = async () => {
  try {
    const { list } = await getCategoryOptions()
    // 动态更新formApi中的category选项
    if (gridApi && gridApi.formApi) {
      gridApi.formApi.updateSchema([
        {
          componentProps: {
            options: list || [],
          },
          fieldName: 'category',
        },
      ])
    }
  } catch (error) {
    console.error('获取商品分类选项失败:', error)
    return []
  }
}

// 获取时间分类选项
const fetchTimeCategoryOptions = async () => {
  try {
    const { list } = await getTimeCategoryOptions()
    // 动态更新formApi中的time_category选项
    if (gridApi && gridApi.formApi) {
      gridApi.formApi.updateSchema([
        {
          componentProps: {
            options: list || [],
          },
          fieldName: 'time_category',
        },
      ])
    }
  } catch (error) {
    console.error('获取时间分类选项失败:', error)
    return []
  }
}

const fetchSupplyOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getSupplyOptions({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: !keyword ? formData.value?.supply_id : '',
    select: true,
  })

  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}

const fetchWarehouseOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getWarehouseOptions({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: !keyword ? formData.value?.warehouse_id : '',
    select: true,
  })

  return list.map((item: any) => ({
    label: item.WarehouseCodeName,
    value: item.id,
  }))
}

const fetchHeelManOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getGoodsHeelMan({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'heel_man_name',
    initValue: !keyword ? formData.value?.heel_man_name : '',
    select: true,
  })

  return list.map((item: any) => ({
    label: item.heel_man_name,
    value: item.heel_man_name,
  }))
}

const fetchMerchandiserOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getMerchandiserDict({
    quick_search: keyword,
    page: 1,
    limit: 100,
    key: 'merchUsers',
    initKey: 'data_value',
    initValue: !keyword ? formData.value?.merchandiser : '',
    select: true,
  })

  return list.map((item: any) => ({
    label: item.data_value,
    value: item.data_value,
  }))
}

// 获取选中行的ID数组
const getSelectionIds = () => {
  return selectedRows.value.map((row: any) => row.id)
}

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Cascader',
      fieldName: 'category',
      label: '货品分类',
      operator: '123',
      componentProps: {
        options: [],
        allowClear: true,
        multiple: true,
        showSearch: true,
        alwaysLoad: true,
        showCheckedStrategy: Cascader.SHOW_CHILD,
        maxTagCount: 'responsive',
        // maxTagCount 设为 'responsive' 时，当标签过多时会自动折叠显示，并在鼠标悬停时显示 tooltip
      },
    },
    {
      component: 'Cascader',
      fieldName: 'time_category',
      label: '时间分类',
      operator: '123',
      componentProps: {
        options: [],
        allowClear: true,
        multiple: true,
        showSearch: true,
        alwaysLoad: true,
        showCheckedStrategy: Cascader.SHOW_CHILD,
        maxTagCount: 'responsive',
        // maxTagCount 设为 'responsive' 时，当标签过多时会自动折叠显示，并在鼠标悬停时显示 tooltip
      },
    },
    {
      component: 'Input',
      fieldName: 'a*goods_purchase_sn',
      label: '采购单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '采购单号',
      },
    },
    {
      component: 'Input',
      fieldName: 'b*goods_no',
      label: '货号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '货号',
      },
    },
    {
      component: 'Input',
      fieldName: 'template*template_no',
      label: '简码',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '简码',
      },
    },
    {
      component: 'Select',
      fieldName: 'is_expired',
      label: '是否到期',
      operator: '123',
      componentProps: {
        options: [
          { label: '已到期', value: '1' },
          { label: '未到期', value: '2' },
        ],
        allowClear: true,
        placeholder: '请选择到期状态',
      },
    },
    {
      component: 'Select',
      fieldName: 'is_completed',
      label: '完成状态',
      operator: '123',
      componentProps: {
        options: [
          { label: '已完成', value: '1' },
          { label: '未完成', value: '0' },
          { label: '已取消', value: '2' },
        ],
        allowClear: true,
        placeholder: '请选择完成状态',
      },
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchSupplyOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.supply_id = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword.value.supply_id || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            keyword.value.supply_id = ''
          },
        }
      },
      fieldName: 'a*supply_id',
      label: '供应商',
      operator: 'IN',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchWarehouseOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.warehouse_id = value
          }, 300),
          params: {
            keyword: keyword.value.warehouse_id || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            keyword.value.warehouse_id = ''
          },
        }
      },
      fieldName: 'a*warehouse_id',
      label: '收货仓库',
      operator: 'IN',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchHeelManOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.heel_man_name = value
          }, 300),
          params: {
            keyword: keyword.value.heel_man_name || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            keyword.value.heel_man_name = ''
          },
        }
      },
      fieldName: 'HeelMan',
      label: '买手',
      operator: '123',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchMerchandiserOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.merchandiser = value
          }, 300),
          params: {
            keyword: keyword.value.merchandiser || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            keyword.value.merchandiser = ''
          },
        }
      },
      fieldName: 'g*merchandiser',
      label: '跟单人',
      operator: 'IN',
    },
    {
      component: 'Select',
      fieldName: 'ee*follow_user',
      label: '发单人',
      operator: 'IN',
      componentProps: {
        options: [
          { label: '蔡成村', value: '蔡成村' },
          { label: '张伟', value: '张伟' },
          { label: '谷冬冬', value: '谷冬冬' },
          { label: '胡长征', value: '胡长征' },
        ],
        mode: 'multiple',
        allowClear: true,
        placeholder: '请选择发单人',
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'a*purchase_date',
      label: '下单日期',
      operator: 'RANGE',
      render: 'datestring',
      componentProps: {
        // format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'b*expected_completion_date',
      label: '交货日期',
      operator: 'RANGE',
      render: 'datestring',
      componentProps: {
        // format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Select',
      fieldName: 'a*purchase_type',
      label: '订单性质',
      operator: 'IN',
      componentProps: {
        options: [
          { label: '成品#首单', value: '8' },
          { label: '加工#补单', value: '9' },
          { label: '加工#首单', value: '10' },
          { label: '成品#补单', value: '11' },
          { label: '成品#加单', value: '12' },
          { label: '加工#加单', value: '13' },
        ],
        allowClear: true,
        mode: 'multiple',
        placeholder: '请选择订单性质',
      },
    },
    // {
    //   component: 'RangePicker',
    //   fieldName: 'ee*expected_launch_date',
    //   label: '预计上线日期',
    //   operator: 'RANGE',
    //   render: 'datestring',
    //   componentProps: {
    //     // format: 'YYYY-MM-DD',
    //     valueFormat: 'YYYY-MM-DD',
    //   },
    // },
    // {
    //   component: 'Select',
    //   fieldName: 'exp_quantity',
    //   label: '超期限制天数',
    //   operator: '123',
    //   render: 'tag',
    //   componentProps: {
    //     options: [
    //       { label: '(按入仓)不显示低于2%', value: '1' },
    //       { label: '(按入仓)显示低于2%', value: '2' },
    //       { label: '(按发货)不显示低于2%', value: '3' },
    //       { label: '(按发货)显示低于2%', value: '4' },
    //     ],
    //     allowClear: true,
    //     placeholder: '请选择复期次数',
    //   },
    // },
    // {
    //   component: 'Select',
    //   fieldName: 'ee*second_procurement_num',
    //   label: '复期次数',
    //   operator: '>',
    //   componentProps: {
    //     options: [
    //       { label: '>1次', value: '1' },
    //       { label: '>2次', value: '2' },
    //       { label: '>3次', value: '3' },
    //       { label: '>4次', value: '4' },
    //       { label: '>5次', value: '5' },
    //       { label: '>6次', value: '6' },
    //       { label: '>7次', value: '7' },
    //     ],
    //     allowClear: true,
    //     placeholder: '请选择复期次数',
    //   },
    // },
    {
      component: 'Select',
      fieldName: 'order_type',
      label: '排序方式',
      operator: '123',
      componentProps: {
        options: [
          { label: '货号-降序', value: 'b.goods_no desc' },
          { label: '货号-升序', value: 'b.goods_no asc' },
          { label: '交货日期-降序', value: 'b.expected_completion_date desc' },
          { label: '交货日期-升序', value: 'b.expected_completion_date asc' },
          { label: '超期天数-降序', value: 'diff_day desc' },
          { label: '超期天数-升序', value: 'diff_day asc' },
          { label: '下单日期-降序', value: 'a.purchase_date desc' },
          { label: '下单日期-升序', value: 'a.purchase_date asc' },
          { label: '订单数-降序', value: 'b.plan_total_num desc' },
          { label: '订单数-升序', value: 'b.plan_total_num asc' },
          { label: '已发货数量-降序', value: 'f.quantity desc' },
          { label: '已发货数量-升序', value: 'f.quantity asc' },
          { label: '加工费-降序', value: 'template.real_template_cost desc' },
          { label: '加工费-升序', value: 'template.real_template_cost asc' },
          { label: '在途数量-降序', value: 'ff.quantity desc' },
          { label: '在途数量-升序', value: 'ff.quantity asc' },
          { label: '已入仓数量-降序', value: 'e.quantity desc' },
          { label: '已入仓数量-升序', value: 'e.quantity asc' },
          { label: '裁床数量-降序', value: 'j.quantity desc' },
          { label: '裁床数量-升序', value: 'j.quantity asc' },
          { label: '退货数量-降序', value: 'g.quantity desc' },
          { label: '退货数量-升序', value: 'g.quantity asc' },
          { label: '跟单交期反馈-降序', value: 'ee.delivery_feedback desc' },
          { label: '跟单交期反馈-升序', value: 'ee.delivery_feedback asc' },
          { label: '跟单-降序', value: 'g.merchandiser desc' },
          { label: '跟单-升序', value: 'g.merchandiser asc' },
          { label: '供应商-降序', value: 'd.SupplyNa desc' },
          { label: '供应商-升序', value: 'd.SupplyNa asc' },
          { label: '发货数与订单数的差异-降序', value: 'cc_chayi_quantity desc' },
          { label: '发货数与订单数的差异-升序', value: 'cc_chayi_quantity asc' },
          { label: '商品预计交期-降序', value: 'shop_num.go_dead_line desc' },
          { label: '商品预计交期-升序', value: 'shop_num.go_dead_line asc' },
          { label: '样衣克重-降序', value: 'ee.sample_cloth_weight desc' },
          { label: '样衣克重-升序', value: 'ee.sample_cloth_weight asc' },
          { label: '样衣尺码-降序', value: 'ee.sample_size desc' },
          { label: '样衣尺码-升序', value: 'ee.sample_size asc' },
          { label: '头版批版结果-降序', value: 'ee.frontpage_approval_result desc' },
          { label: '头版批版结果-升序', value: 'ee.frontpage_approval_result asc' },
        ],
        allowClear: true,
        placeholder: '请选择排序方式',
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  showFooter: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    //  isCurrent: true,
    isHover: true,
  },
  columnConfig: {
    useKey: true,
  },
  columns: [],
  height: 'auto',
  size: 'mini',
  keepSource: true,
  pagerConfig: {
    pageSize: 30,
  },
  scrollX: {
    gt: 20,
  },
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: async ({ page }, formValues) => {
        const search = await gridApi.formApi.getFiltersValues(formValues)
        const apiFunction = dataType.value === '1' ? getPurchaseIndex : getPurchaseIndex2
        const searchParams = search.length > 0 ? search : [{ field: 'ee.follow_user', operator: 'IN', val: [] }]
        var data = await apiFunction({
          page: page.currentPage,
          limit: page.pageSize,
          op: '1',
          search: searchParams,
        })
        // console.log('list', data.list)
        columnsInit(data)

        console.log('data', data)
        return {
          items: data.list,
          total: data.total,
        }
      },
    },
  },
  cellClassName: ({ row, column }) => {
    if (column.field === 'ml_null_num' || column.field === 'fl_null_num') {
      return 'text-[#4e69fd] underline'
    }
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'goods_purchase_progress_2_list',
  customConfig: {
    storage: true,
  },
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    cellClick: ({ row, column }) => {
      if (column.field === 'second_procurement_review') {
        AgainModalApi.setData({
          info: row,
          isEdit: false,
        }).open()
      }else if(column.field === 'ml_null_num'){
        TypeLogModalApi.setData({
          info: row,
        }).open()
      }else if(column.field === 'fl_null_num'){
        TypeLogModalApi.setData({
          info: row,
        }).open()
      }
    },
    menuClick: ({ menu, row, column }) => {
      switch (menu.code) {
        case 'editRow':
          if (row) {
            if (column.field === 'second_procurement_review') {
              // message.info(`复期: ${menu.name}`)
              AgainModalApi.setData({
                info: row,
                isEdit: true,
              }).open()
            } else {
              gridApi.grid.setEditRow(row)
            }
          }
          break
        case 'copy':
          if (row && column) {
            copyToClipboard(row[column.field])
          }
          break
        case 'copyRow':
          if (row) {
            const columns = gridApi.grid.getColumns()
            const header = columns.map((col: any) => ({
              label: col.title,
              value: col.field,
            }))
            copyToClipboard([row], header)
          }
          break
        default:
          message.info(`点击了菜单: ${menu.name}`)
      }
    },
  },
})

// 初始化表格列
const columnsInit = (res: any) => {
  header_data.value = res.header_data
  header_info.value = res.header_info
  field_data.value = res.field_data

  if (header_info.value && header_info.value.length > 0) {
    const dynamicColumns = header_info.value.map((col: any, index: number) => {
      const fieldConfig = field_data.value.find((f: any) => f.data === col.value) || {}
      let editRender = {}
      let cellRender = {}

      if (fieldConfig.is_write) {
        if (fieldConfig.type === 'date') {
          editRender = {
            name: 'CellDatePicker',
            props: { valueFormat: 'YYYY-MM-DD' },
          }
        } else if (fieldConfig.editor === 'select') {
          editRender = {
            name: 'CellSelect',
            options: fieldConfig.selectOptions.map((item: any) => ({ label: item, value: item })) || [],
          }
        } else {
          editRender = {
            name: 'CellInput',
          }
        }
      }
      if (col.value === 'goods_image') {
        cellRender = {
          name: 'CellImage',
        }
      }
      return {
        field: col.value,
        title: col.label,
        width: fieldConfig.width || '80px',
        visible: !fieldConfig.className ? false : true,
        ...(fieldConfig.is_write && { editRender }),
        cellRender,
      }
    })

    gridApi.grid.loadColumn(dynamicColumns)
  }
}

// 导出功能
const handleExport = async () => {
  const hide = message.loading('正在导出...', 0)
  try {
    const search = await gridApi.formApi.getFiltersValues()
    const apiFunction = dataType.value === '1' ? exportPurchaseProgress : exportPurchaseProgress2
    await apiFunction({
      search,
      is_exp: true,
    })
  } catch (e) {
    message.error('导出失败')
  } finally {
    hide()
  }
}

// 下载导出模版
const handleUrl = async () => {
  window.location.href = `${import.meta.env.VITE_GLOB_API_URL}/static/template/物料档案导入格式.xlsx`
}

// 保存编辑
const handleSave = async () => {
  if (gridApi) {
    const updateRecords = gridApi.grid.getUpdateRecords()
    // console.log(updateRecords)
    if (updateRecords.length > 0) {
      await savePurchaseProgress({ data: updateRecords })
        .then(() => {
          message.success('保存成功')
          gridApi.query()
        })
        .catch(() => {
          message.error('保存失败')
        })
    }
  }
}

// 数据类型切换
const handleDataTypeChange = (value: any) => {
  dataType.value = value.target.value
  gridApi.query()
}

// 弹窗组件
const [SendGoodsSkuModal, SendGoodsSkuModalApi] = useVbenModal({
  connectedComponent: SendGoodsSkuModalComponent,
})

// 操作：查看SKU详情
const handleViewSku = (row: RowType, type: string) => {
  SendGoodsSkuModalApi.setData({
    title: `采购单号:${row.goods_purchase_sn},货号:${row.goods_no}-已发货数量明细`,
    goods_purchase_sn: row.goods_purchase_sn,
    goods_id: row.goods_id,
  }).open()
}

const handleSearchTemplate = async () => {
  SearchTemplateModalApi.open()
}

// 弹窗组件
const [AgainModal, AgainModalApi] = useVbenModal({
  connectedComponent: Again,
})

// 弹窗组件
const [TypeLogModal, TypeLogModalApi] = useVbenModal({
  connectedComponent: TypeLog,
})

// 弹窗组件
const [SearchTemplateModal, SearchTemplateModalApi] = useVbenModal({
  connectedComponent: SearchTemplate,
})

// 获取到期状态颜色
const getExpiredColor = (row: RowType) => {
  return row.is_expired === 1 ? 'error' : 'success'
}

// 获取完成状态颜色
const getCompletedColor = (row: RowType) => {
  return row.is_completed === 0 ? 'warning' : 'success'
}

// 获取超期天数颜色
const getDiffDayColor = (row: RowType) => {
  return row.diff_day > 0 ? 'error' : 'success'
}
// 获取字段配置
const getFieldConfig = (fieldName: string) => {
  return field_data.value.find((f: any) => f.data === fieldName) || {}
}

async function openPrompt() {
  prompt<string>({
    componentProps: {},
    title: '保存搜索条件',
    content: '自定义名称',
    // icon: 'question',
    overlayBlur: 3,
  })
    .then(async (res) => {
      // message.success(`用户输入了：${res}`)
      if (res) {
        const formValues = await gridApi.formApi.getValues()
        // 将对象转换为数组格式
        // const contentArray = Object.entries(formValues).map(([key, value]) => ({
        //   key,
        //   value,
        // }))
        saveSearchTemplate({
          title: res,
          data_type: dataType.value,
          group_name: 'goodsPurchaseProgress2',
          content: formValues,
        }).then(() => {
          message.success('保存成功')
        })
      }
    })
    .catch(() => {
      message.error('用户取消了输入')
    })
}

// 搜索条件选择框改变时，获取搜索条件内容
const changeWhere = async (value: any, content?: any) => {
  if (value && content) {
    // 将content中的key里的.替换为*
    const processedContent: any = {}
    Object.keys(content).forEach((key) => {
      const newKey = key.replace(/\./g, '*')
      processedContent[newKey] = content[key]
    })
    await gridApi.formApi.resetForm()
    await gridApi.formApi.setValues(processedContent)
  }
}

const fetchData = async () => {
  gridApi.reload()
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button type="ghost" class="mr-2 bg-[#cf892d] text-white hover:opacity-75" @click="handleUrl">下载导入模版</Button>
        <Button type="ghost" class="mr-2 bg-[#24b916] text-white hover:opacity-75" @click="handleExport">导出数据</Button>
        <Button type="ghost" class="mr-2 bg-[#006be6] text-white hover:opacity-75" @click="handleSave">保存编辑</Button>
        <Button type="ghost" class="mr-2 bg-[#16b9b1] text-white hover:opacity-75" @click="handleSearchTemplate">条件管理</Button>
        <Button type="ghost" class="mr-2 bg-[#3c72e6] text-white hover:opacity-75" @click="openPrompt">保存条件</Button>
        <div>
          <SearchTemplateSelect @change="changeWhere" />
        </div>
      </template>
      <template #toolbar-tools>
        <Radio.Group v-model:value="dataType" @change="handleDataTypeChange" class="ml-4">
          <Radio.Button value="1">实时取数</Radio.Button>
          <Radio.Button value="2">快照取数</Radio.Button>
        </Radio.Group>
      </template>

      <template #goodsNo="{ row }">
        <Button type="link" @click="handleViewSku(row, 'send')">{{ row.goods_no }}</Button>
      </template>

      <template #isExpiredText="{ row }">
        <Tag :color="getExpiredColor(row)">
          {{ row.is_expired_text }}
        </Tag>
      </template>

      <template #isCompletedText="{ row }">
        <Tag :color="getCompletedColor(row)">
          {{ row.is_completed_text }}
        </Tag>
      </template>

      <template #sendQuantity="{ row }">
        <Button type="link" @click="handleViewSku(row, 'send')">{{ row.send_quantity }}</Button>
      </template>

      <template #diffDay="{ row }">
        <span :style="{ color: getDiffDayColor(row) === 'error' ? 'red' : '' }">
          {{ row.diff_day }}
        </span>
      </template>

      <template #operation="{ row }">
        <!-- <Button class="mr-2" type="primary" size="small" @click="handleViewSku(row, 'send')">查看明细</Button> -->
      </template>
    </Grid>
    <SendGoodsSkuModal />
    <AgainModal @fetch-data="fetchData" />
    <SearchTemplateModal />
    <TypeLogModal />
  </Page>
</template>
